import {
  CanActivate,
  ExecutionContext,
  HttpException,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { Request } from 'express';
import { JwtService } from '@nestjs/jwt';
import { Reflector } from '@nestjs/core';
import { RequrieLoginKey } from 'src/cu-dec/cu-dec';

declare module 'express' {
  interface Request {
    user: {
      username: string;
      id: number;
      roles: number[];
    };
  }
}

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(
    private readonly jwtService: JwtService,
    private readonly refector: Reflector,
  ) {}
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const request: Request = context.switchToHttp().getRequest();

    const requrieLogin = this.refector.getAllAndOverride(RequrieLoginKey, [
      context.getHandler(),
      context.getClass(),
    ]);

    console.log(requrieLogin);

    if (!requrieLogin) return true;

    const token = request.headers.authorization;
    if (!token) throw new HttpException('用户未登录', 401);

    try {
      const data = this.jwtService.verify(token);
      request.user = data;
      return true;
    } catch (error) {
      throw new UnauthorizedException('登录过期');
    }
  }
}
